package com.ido.news.splashlibrary.presenter

import android.util.Log
import com.dotools.umlibrary.UMPostUtils
import com.dotools.utils.PackageUtils
import com.google.gson.Gson
import com.ido.news.splashlibrary.bean.BeanResponse
import com.ido.news.splashlibrary.callback.HttpCallBack
import com.ido.news.splashlibrary.contract.SplashContract
import com.ido.news.splashlibrary.model.BaseSplashModelImpl
import com.ido.news.splashlibrary.util.Constant
import com.ido.news.splashlibrary.util.SPGlobalConfigMgr
import java.util.*
import kotlin.collections.HashMap

class BaseSplashPresenterImpl : SplashContract.BaseSplashPresenter() {
    private var mModel: SplashContract.BaseSplashModel? = null
    private var mView: SplashContract.BaseSplashView? = null
    private var sdkIndex = 0//sdk轮播位置
    private var mResponse: BeanResponse? = null

    override fun onAttach(viewBase: SplashContract.BaseSplashView) {
        this.mView = viewBase
        if (mModel == null) {
            mModel = BaseSplashModelImpl()
        }
    }

    override fun onDetach() {
        try {
            if (mModel != null) {
                mModel!!.cancelRequest()
                mModel!!.DBClose()
                mModel = null
            }
            sdkIndex = 0
        } catch (e: Exception) {
            e.printStackTrace()
            val stackTraceElement = e.stackTrace[0]// 得到异常棧的首个元素
            val map = HashMap<String, String>()
            map["detachError"] =
                "File=" + stackTraceElement.fileName + "-" + "Line=" + stackTraceElement.lineNumber + "-" + "Method=" + stackTraceElement.methodName
            UMPostUtils.onEventMap(mView!!.getContext(), "flash_failed", map)
        }
    }


    /**
     * 获取服务器数据
     */
    override fun getResponse() {
        sdkIndex = 0
        mModel!!.getResponse(mView!!.getContext(),
            Constant.SERVER,
            PackageUtils.getUmengChannel(mView!!.getContext()),
            mView!!.getContext().packageName,
            PackageUtils.getVersionCode(mView!!.getContext()).toString(),
            object : HttpCallBack {
                override fun onSuccess(responseJson: String) {
                    if (mView != null) {
                        if (responseJson != "") {
                            try {
                                UMPostUtils.onEvent(mView!!.getContext(), "flash_pullsucceed")
                                val gao = Gson()
                                mResponse = gao.fromJson(responseJson, BeanResponse::class.java)
                                val newUser = isNewUser()
                                when (mResponse!!.statusCode) {
                                    200 -> {
                                        mModel!!.saveCache(mView!!.getContext(), responseJson)
                                        successResponse(mResponse!!)
                                    }
                                    4022044 -> {
                                        if (!newUser) {
                                            mResponse = null
                                            cacheResponse()
                                        } else {
                                            mView!!.onError("AD SWITCH OFF")
                                        }
                                    }
                                    else -> {
                                        val map = HashMap<String, String>()
                                        map["error"] = "Response: code:" + mResponse!!.statusCode + " msg:" + mResponse!!.errorMsg
                                        UMPostUtils.onEventMap(mView!!.getContext(), "flash_pullfailed", map)
                                        cacheResponse()
                                    }
                                }
                            } catch (e: Exception) {
                                val map = HashMap<String, String>()
                                map["error"] = e.message.toString()
                                UMPostUtils.onEventMap(mView!!.getContext(), "flash_pullfailed", map)
                                Log.e(Constant.Tag, "JSONException:" + e.message.toString())
                                cacheResponse()
                            }
                        } else {
                            val map = HashMap<String, String>()
                            map["error"] = " ResponseJson is NULL"
                            UMPostUtils.onEventMap(mView!!.getContext(), "flash_pullfailed", map)
                            Log.e(Constant.Tag, "ResponseJson is NULL")
                            cacheResponse()
                        }
                    } else {
                        mView!!.onError("onSuccess View  Is NULL")
                    }
                }

                override fun onFail(errMsg: String) {
                    if (mView != null) {
                        val map = HashMap<String, String>()
                        map["error"] = errMsg
                        UMPostUtils.onEventMap(mView!!.getContext(), "flash_pullfailed", map)
                        Log.e(Constant.Tag, errMsg)
                        cacheResponse()
                    } else {
                        mView!!.onError("onFail View  Is NULL")
                    }
                }
            })
    }

    /**
     * 拉取成功处理
     */
    private fun successResponse(response: BeanResponse) {
        try {
            setResponseIndex(response, false)
        } catch (e: Exception) {
            e.printStackTrace()
            mView!!.onError(e.message!!)
        }
    }


    /**
     * 拉取服务器失败缓存处理
     */
    private fun cacheResponse() {
        if (mResponse == null) {
            if (mView != null) {
                mResponse = mModel?.getCache(mView!!.getContext())
            }
        }
        if (mResponse != null) {
            setResponseIndex(mResponse!!, true)
        } else {
            mView!!.onError("NoCache")
        }
    }

    private fun setResponseIndex(response: BeanResponse, isCache: Boolean) {
        if (response.data.size > 0) {
            var index = SPGlobalConfigMgr.getLunBoIndex(mView!!.getContext())
            if (index > response.data.size - 1) {
                index = 0
            }
            //判断广告开关
            if (response.data[index].isAdIsOpen) {
                SPGlobalConfigMgr.setLunBoIndex(mView!!.getContext(), index + 1)
                handleResponse(response, index, sdkIndex, isCache)
            } else {
                mView!!.onError("AD Switch Close")
            }
        } else {
            mView!!.onError("Data Size IS 0")
        }
    }

    /**
     *SDK广告拉取失败缓存处理
     */
    override fun SDKFail() {
        sdkIndex += 1
        cacheResponse()
    }

    private fun isNewUser(): Boolean {
        val version = SPGlobalConfigMgr.getVersionFlag(mView!!.getContext())
        return if (version == -1) {
            SPGlobalConfigMgr.setVersionFlag(mView!!.getContext(), PackageUtils.getVersionCode(mView!!.getContext()))
            true
        } else {
            version >= PackageUtils.getVersionCode(mView!!.getContext())
        }
    }


    /**
     * 判断广告类型是自营还是广点通和头条
     * 新版本json的	adExtendData改成了数组模式"adExtendData": "{\"sequence\":[\"TOUTIAO\",\"GDT\"],\"self\":{\"mtPackageName\":null,\"mtVersionCode\":100,\"mtType\":\"OPEN\",\"mtUrl\":\"http://interaction.bayimob.com/gameHtml?appkey=75687f9976d4d2d7c987af989e211d1c&adSpaceKey=ebb23669a10f938b71098e1681e902a3\",\"mtImage\":\"http://oss.idourl.com/upload/20180830/image_1cm4lbe2m1hbq1t5e1i87r5esi5b.png\"}}"
     * 旧版本json的adExtendData是String模式adExtendData : {"mtPackageName":"com.dotools.weather","mtVersionCode":"200","mtType":"DOWNLOAD","mtUrl":"http://balance2.chinacloudapp.cn/com.dotools.weather_gjx.apk","mtImage":"http://oss.tv163.com/toolbox/d74e8e64-8afa-4e65-8f3d-b7898d1959e3.png"}
     * 所以兼容新版和旧版处理  正常来说新版是不会出现先展示自营的情况   先展示自营会使用旧版展示
     */
    private fun handleResponse(response: BeanResponse, index: Int, sdkIndex: Int, isCache: Boolean) {
        try {
            val supportType = response.data[index].adSupportType
            when (supportType) {
                Constant.FIRST_TX, Constant.TX, Constant.TOUTIAO, Constant.KS, Constant.BD -> {//旧版
                    if (isCache) {
                        UMPostUtils.onEvent(mView!!.getContext(), "flash_cache_sdk")
                    } else {
                        UMPostUtils.onEvent(mView!!.getContext(), "flash_pullsucceedsdk")
                    }
                    if (sdkIndex > response.data.size - 1) {
                        showOldSelf(response, index)
                    } else {
                        mView!!.showOtherSDK(supportType, 0, 0)
                    }
                }
                Constant.THREE_SEQUENCE -> {//新版
                    val extendDataMap = response.data[index].extendDataMap
                    if (extendDataMap != null) {
                        var showMode = 0.0
                        var downloadMode = 0.0
                        if (extendDataMap.containsKey("sequence")) {
                            val sequence = extendDataMap["sequence"] as ArrayList<String>
                            if (sdkIndex < sequence.size) {
                                if (isCache) {
                                    UMPostUtils.onEvent(mView!!.getContext(), "flash_cache_sdk")
                                } else {
                                    UMPostUtils.onEvent(mView!!.getContext(), "flash_pullsucceedsdk")
                                }
                                if (extendDataMap.containsKey("showMode")) {//闪屏显示模式
                                    showMode = extendDataMap["showMode"] as Double
                                }
                                if (extendDataMap.containsKey("downloadMode")) {//下载弹窗提示模式
                                    downloadMode = extendDataMap["downloadMode"] as Double
                                }
                                mView!!.showOtherSDK(sequence[sdkIndex], showMode.toInt(), downloadMode.toInt())
                            } else {
                                showNewSelf(response, index)
                            }
                        } else {
                            showNewSelf(response, index)
                        }
                    } else {
                        showNewSelf(response, index)
                    }
                }
                else -> {//自营
                    showOldSelf(response, index)
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
            mView!!.onError(e.message!!)
        }
    }


    private fun showOldSelf(response: BeanResponse, index: Int) {
        val selfDataMap = response.data[index].oldSelfDataMap
        val id = response.data[index].adVid!!.substring(0, 6)
        val imgUrl = selfDataMap["mtImage"]!!
        val clickUrl = selfDataMap["mtUrl"]!!
        val packageName = selfDataMap["mtPackageName"]
        if (selfDataMap["mtType"] == "OPEN") {
            mView!!.setOpenClick(clickUrl, index, id)
        } else {
            mView!!.setDownloadClick(
                clickUrl,
                selfDataMap["mtName"]!!,
                packageName!!,
                selfDataMap["mtIcon"]!!,
                index,
                id
            )
        }
        mView!!.showImg(imgUrl, id)
    }

    private fun showNewSelf(response: BeanResponse, index: Int) {
        val selfJson = response.data[index].extendDataMap["self"] as Map<String, String>
        val id = response.data[index].adVid!!.substring(0, 6)
        val imgUrl = selfJson["mtImage"]
        val clickUrl = selfJson["mtUrl"]
        val packageName = selfJson["mtPackageName"]
        if (selfJson["mtType"] == "OPEN") {
            mView!!.setOpenClick(clickUrl!!, index, id)
        } else {
            mView!!.setDownloadClick(
                clickUrl!!,
                selfJson["mtName"]!!,
                packageName!!,
                selfJson["mtIcon"]!!,
                index,
                id
            )
        }
        UMPostUtils.onEvent(mView!!.getContext(), "flash_ziying_show")
        mView!!.showImg(imgUrl!!, id)
    }

}